#include "stdafx.h"
#include "Packet.h"
#include "baseserver.h"
#include ".\simpleencrypt.h"
namespace Lumin {
namespace Win32 {

PACKET::PACKET()
{
	m_pStream = CBaseServer::Allocate();
	m_pStream->AddRef();
}

PACKET::~PACKET(void)
{
	if(m_pStream != NULL)
		m_pStream->Release();
}

void PACKET::Flush()
{
	PACKETHEAD* pHdr = (PACKETHEAD*)GetBuffer();
	pHdr->length = ::htons(GetSize());
}

short PACKET::GetSize()
{
	return m_pStream->GetSize();
}

void PACKET::AddStream(const void* lpBuf, size_t length)
{
	if(!m_pStream->PushData((char*)lpBuf,length)){
		throw CPacketException("write data over size!");
	}
}

void PACKET::GetStream(void* lpBuf, size_t length)
{
	if(length > m_pStream->GetSize()){
		throw CPacketException("read data over size");
	}
	memcpy(lpBuf,m_pStream->GetData(),length);
	m_pStream->PopData(length);
}

PACKET* PACKET::SplitPacket(size_t length)
{
	PACKET *pPacket = new PACKET();
	GetStream(pPacket->GetBuffer(),length);
	pPacket->m_pStream->SetSize(length);
	return pPacket;
}

char* PACKET::GetBuffer()
{
	return m_pStream->GetData();
}

void *PACKET::operator new(size_t objectSize)
{
	return CPoolMgr<PACKET>::GetInstance()->Allocate(objectSize);
}

void PACKET::operator delete(void *pObject, size_t /* bufferSize*/)
{
	CPoolMgr<PACKET>::GetInstance()->Free(pObject);
}
///////////////////////////////////////////////////////////////////////////////
// Namespace: Lumin::Win32
///////////////////////////////////////////////////////////////////////////////

} // End of namespace Win32
} // End of namespace Lumin 
